package com.lhn.controller;

import com.lhn.entity.Menu;
import com.lhn.entity.ResponseMsg;
import com.lhn.feign.MenuFeign;
import feign.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author lhn
 * @date 2024-10-09 21:26
 */

//@RestController
@Controller //返回值的类型可以是视图名称（通常是字符串），也可以是 ModelAndView 对象。当返回字符串时，Spring 会将其解析为视图名称，并使用视图解析器（如 JSP、Thymeleaf 等）来渲染视图。
@RequestMapping("consumer")
public class MenuController {

    @Autowired
    private MenuFeign menuFeign;

    @GetMapping("/redirect/{location}")
    public String redirect(@PathVariable("location") String location) {
        return location;
    }

    @GetMapping("menu/findAll")
    @ResponseBody   // 返回json数据
    public ResponseMsg<List<Menu>> findAll(@Param("page") int page, @Param("limit") int limit) {
        int index = (page - 1) * limit;
        return new ResponseMsg<>("0", "", menuFeign.count(), menuFeign.findAll(index, limit));
    }

    @GetMapping("menu/findAllWithType")
    @ResponseBody   // 返回json数据
    public ResponseMsg<List<Menu>> findAllWithType(@Param("page") int page, @Param("limit") int limit) {
        int index = (page - 1) * limit;
        return new ResponseMsg<>("0", "", menuFeign.count(), menuFeign.findAllWithType(index, limit));
    }

    @GetMapping("menu/count")
    @ResponseBody
    public int count() {
        return menuFeign.count();
    }

    @PostMapping("menu/save")
    public String save(Menu menu) {
        menuFeign.save(menu);
        return "redirect:/consumer/redirect/menu_manage";
    }

    @GetMapping("menu/findById/{id}")
    public ModelAndView findById(@PathVariable("id") long id) {
        System.out.println("findById 's id is " + id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("menu_update");
        modelAndView.addObject("menu", menuFeign.findById(id));
        modelAndView.addObject("list", menuFeign.findAllType());
        return modelAndView;
    }

    @GetMapping("menu/deleteById/{id}")
    public String deleteById(@PathVariable("id") long id) {
        menuFeign.deleteById(id);
        return "redirect:/consumer/redirect/menu_manage";
    }

    @PostMapping("menu/update")
    public String update(Menu menu) {
        menuFeign.update(menu);
        return "redirect:/consumer/redirect/menu_manage";
    }

    @GetMapping("type/findAllType")
    public ModelAndView findAll() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("menu_add");
        modelAndView.addObject("list", menuFeign.findAllType());
        return modelAndView;
    }

}
